const router = require('koa-router')()
const svgCaptcha = require("svg-captcha")
const fs = require('fs');
const jwt = require("jsonwebtoken");
const myKey = "1234"

let user
fs.readFile('userdata.json', 'utf-8', (err, data) => {
  user = JSON.parse(data.toString());
})

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})
router.get('/svg', async (ctx, next) => {
  console.log(555)
  let options = {
    size: 4,
    noise: 2,
    color: true,
    background: "#666",
    whith: 70,

  }

  let captcha = svgCaptcha.create(options) //字母和数字随机验证码


  return ctx.body = captcha

})
router.post("/login", async (ctx, next) => {
  const username = ctx.request.body.username;
  const password = ctx.request.body.password;
  ctx.body = "false"


  for (var i = 0; i < user.length; i++) {
    console.log(user[i].username)
    if (username == user[i].username && password == user[i].password) {
      let token = jwt.sign({ "username": username }, myKey);
      ctx.body = { token: token, status: "ok" };

    }

  }


  return ctx.body

})



router.post("/upload", async (ctx, next) => {
  let authorization = ctx.header.token

  if (authorization == undefined) {
    ctx.body = false
  }
  else {
    let result = jwt.verify(authorization, myKey);
    if (result.username) {

      ctx.body = { "status": "success" };
    }
    else {
      ctx.body = false
    }

  }
  return ctx.body
})



module.exports = router
